package com.edee.bigday.seckill.interceptor;

import com.edee.common.constant.AuthServerConstant;
import com.edee.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    //为了线程间共享，使用ThreadLocal：
    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //  /order/order/status/{orderSn}---->/order/order/status/2340921349808
        //使用Spring的匹配器进行匹配放行路径：
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", requestURI);
        if (match) {
            //如果是秒杀请求，进行如下处理：
            MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
            if (attribute != null) {
                loginUser.set(attribute);
                return true;
            } else {
                //增加登录提示信息：
                request.getSession().setAttribute("msg", "登录之后，才能正常使用秒杀服务！");
                //重定向到登录页：
                response.sendRedirect("http://auth.bigday.com/login.html");
                return false;
            }
        }
        //如果不是秒杀请求，直接放行
        return true;
    }
}
